<template>
  <el-form :rules="rules" label-width="80px" :model="form" ref="lv1Form">
    <el-form-item label="分类ID" prop="class1">
      <el-input v-model="form.class1" :disabled="!modeAdd"></el-input>
    </el-form-item>
    <el-form-item label="分类名" prop="class1name">
      <el-input v-model="form.class1name"></el-input>
    </el-form-item>
    <!-- <el-form-item label="分类图片" prop="class1image">
      <upload-image :src="src" :upload="handleUpload" size="small"></upload-image>
    </el-form-item> -->
    <el-form-item>
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button plain @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import UploadImage from './UploadImage.vue'
  import { addClass1, uploadPicToDir, updateClass1 } from '../service/api'
  import { mapActions, mapMutations } from 'vuex'
  export default {
    name: 'lv1-form-editing',
    props: ['form', 'reset', 'isEdit'],
    components: {
      UploadImage
    },
    data () {
      return {
        rules: {
          class1: [{ required: true }],
          // class1image: [{ required: true }],
          class1name: [{ required: true }]
        }
      }
    },
    computed: {
      src () {
        return this.$apath + 'group/' + this.form.class1image
      },
      modeAdd () {
        return !this.isEdit
      }
    },
    methods: {
      ...mapMutations('ci', ['setExpired']),
      ...mapActions('ci', ['fetchLv1']),
      cancel () {
        this.$emit('close')
        this.$refs['lv1Form'].resetFields()
      },
      submit () {
        this.$refs['lv1Form'].validate((valid) => {
          if (!valid) return
          /* 提交 */
          this.handleSubmit()
        })
      },
      /* 处理图片 */
      async handleUpload (file) {
        console.log(file)
        const { data } = await uploadPicToDir({ photo: file, filePath: this.$upath + 'group/' })
        if (!data || +data.code !== 200) {
          this.$message.error('上传失败')
          return
        }
        this.form = { ...this.form, class1image: data.result }
      },
      async handleSubmit () {
        const { data } = this.modeAdd ? await addClass1(this.form) : await updateClass1(this.form)
        if (!data || +data.code !== 200) {
          this.$message.error('操作失败')
          return
        }
        this.$message.success('操作成功')
        this.cancel()
        // @todo 更新本地classify store
        this.setExpired()
        this.fetchLv1()
      }
    },
    watch: {
      reset () {
        this.$refs['lv1Form'].resetFields()
      }
    }
  }
</script>

<style>

</style>
